package com.wfuhui.book.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.wfuhui.book.R;
import com.wfuhui.book.model.Jieyue;
import com.wfuhui.book.model.Order;
import com.wfuhui.book.model.OrderBook;
import com.wfuhui.book.util.Constant;
import com.wfuhui.book.util.GlideImageLoader;
import com.wfuhui.book.util.PreferencesService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 借阅订单
 */
public class JieYueActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView order;

    private List<Jieyue> orderList = new ArrayList<>();

    private JieyueAdapter jieyueAdapter = new JieyueAdapter();

    private TextView statusAll, statusBorrowing, statusReturned;

    private Integer status = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jieyue);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        order = findViewById(R.id.order);
        order.setAdapter(jieyueAdapter);
        getOrder();

        statusAll = findViewById(R.id.statusAll);
        statusAll.setOnClickListener(this);
        statusBorrowing = findViewById(R.id.statusBorrowing);
        statusBorrowing.setOnClickListener(this);
        statusReturned = findViewById(R.id.statusReturned);
        statusReturned.setOnClickListener(this);


    }


    private void setSelected(TextView tv){
        statusAll.setTextColor(getResources().getColor(R.color.black));
        statusBorrowing.setTextColor(getResources().getColor(R.color.black));
        statusReturned.setTextColor(getResources().getColor(R.color.black));
        tv.setTextColor(getResources().getColor(R.color.colorAccent));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.statusAll:
                setSelected(statusAll);
                status = -1;
                getOrder();
                break;
            case R.id.statusBorrowing:
                setSelected(statusBorrowing);
                status = 1;
                getOrder();
                break;
            case R.id.statusReturned:
                setSelected(statusReturned);
                status = 2;
                getOrder();
                break;
        }
    }

    class JieyueAdapter extends BaseAdapter {
        List<Jieyue> mdatas = new ArrayList<>();

        public void setMdatas(List<Jieyue> mdatas) {
            this.mdatas = mdatas;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mdatas.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View v = LayoutInflater.from(JieYueActivity.this).inflate(R.layout.jieyue_item, null);
            final Jieyue order = mdatas.get(i);

            TextView num = v.findViewById(R.id.num);
            num.setText(order.getOrderNum());
            TextView date = v.findViewById(R.id.date);
            date.setText(order.getStartDate() + "~" + order.getEndDate());
            LinearLayout bookLayout = v.findViewById(R.id.book);
            View book = LayoutInflater.from(JieYueActivity.this).inflate(R.layout.order_book_item, null);
            TextView name = book.findViewById(R.id.name);
            name.setText(order.getBookname());
            new GlideImageLoader().displayImage(JieYueActivity.this, order.getBookimage(), (ImageView)book.findViewById(R.id.pic));

            bookLayout.addView(book);
            ((TextView) book.findViewById(R.id.author)).setText(order.getBookauthor());
            ((TextView) book.findViewById(R.id.price)).setText("￥："+order.getBookprice()+"");
            final Button evaluation = v.findViewById(R.id.returnbook);
            if(order.getOrderStatus() == 1){
                evaluation.setVisibility(View.VISIBLE);
            }else
                evaluation.setVisibility(View.GONE);
            if(order.getOrderStatus()==1) {
                ((TextView) v.findViewById(R.id.date)).setText(order.getStartDate());
            }
            if(order.getOrderStatus()==2) {
                ((TextView) v.findViewById(R.id.date)).setText(order.getStartDate() + "~" + order.getEndDate());
            }
            evaluation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    returnbook(mdatas.get(i).getId());
                }
            });

            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
            return v;
        }
    }

    private void returnbook(Integer id) {
        PreferencesService preferencesService = new PreferencesService(this);
        String token = preferencesService.get("token");
        if(token == null || "".equals(token)){
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/jieyue/returnBook/"+id)
                .addHeader("token", token)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/jieyue/returnBook", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/jieyue/returnBook", "onResponse: " + result);
                getOrder();

            }
        });
    }

    private void getOrder(){
        orderList.clear();
        PreferencesService preferencesService = new PreferencesService(this);
        String token = preferencesService.get("token");
        if(token == null || "".equals(token)){
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/jieyue/list?status="+status)
                .addHeader("token", token)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/jieyue/list", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/jieyue/list", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if(code == 0){
                        JSONArray orderArr = json.getJSONArray("orderList");
                        List<String> picUrls = new ArrayList<String>();
                        for(int i = 0; i < orderArr.length(); i++){
                            JSONObject orderJson = orderArr.getJSONObject(i);
                            Jieyue order = new Jieyue();
                            order.setId(orderJson.getInt("id"));
                            order.setOrderNum(orderJson.getString("orderNum"));
                            order.setStartDate(orderJson.getString("startDate"));
                            order.setEndDate(orderJson.getString("endDate"));
                            order.setOrderStatus(orderJson.getInt("orderStatus"));
                            order.setBookauthor(orderJson.getString("bookauthor"));
                            order.setBookname(orderJson.getString("bookname"));
                            order.setBookprice(orderJson.getDouble("bookprice"));
                            order.setBookimage(orderJson.getString("bookimage"));
                            orderList.add(order);
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                jieyueAdapter.setMdatas(orderList);
                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        //返回按钮点击事件
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
